/*
 *Copyright(c) 2021 Shenzhen Kaihong Digital Industry DevelopmentCo.,Ltd
 *Licensed under the Apache License,Version2.0(the"License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS"BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chinasoft.controller;

import com.chinasoft.annotation.OperationLog;
import com.chinasoft.service.impl.ExcelHandler;
import com.chinasoft.utils.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Calendar;
import java.util.Random;

/**
 * 业务类型菜单
 * @author dengtao
 */

@CrossOrigin
@RestController
@RequestMapping("/data")
@Api(tags = "测试",description = "测试")
public class ImportController {

    private static final Logger logger = LoggerFactory.getLogger(ImportController.class);

    @Autowired
    private ExcelHandler excelHandler;

    @ApiOperation(value = "导入")
    @PostMapping("/import")
    @OperationLog(action = "导入", operateType = "import")
    public ResultVO importInit(MultipartFile file) {
        ResultVO resultVo = new ResultVO();
        try {
            String fileName = wirte(file);
            excelHandler.getListByExcel(file.getInputStream(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
            resultVo.setCode(ResultVO.FAIL);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }

    private String wirte(MultipartFile file) throws Exception{
        String originalFilename = file.getOriginalFilename();
        String filenameWithoutSuffix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = filenameWithoutSuffix + suffix;
        String imagePathRoot = "/opt/data/autotool/";
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            imagePathRoot = "C:/ImportData";
        }
        isChartPathExist(imagePathRoot);
        String packagePathUrl = imagePathRoot + File.separator + newFileName;
        System.err.println("packagePathUrl==" + packagePathUrl);
        write(packagePathUrl, file.getInputStream());
        return packagePathUrl;
    }

    private static String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();
        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";
        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);
        return RandomFilename;
    }

    public static void isChartPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 写入文件
     *
     * @param target
     * @param src
     * @throws IOException
     */
    public static void write(String target, InputStream src) throws IOException {
        OutputStream os = new FileOutputStream(target);
        byte[] buf = new byte[1024];
        int len;
        while (-1 != (len = src.read(buf))) {
            os.write(buf, 0, len);
        }
        os.flush();
        os.close();
    }
}
